# src/api/endpoints/management/documents.py 最顶部
import sys
from pathlib import Path
from typing import List, Dict, Any  # 明确导入Any，修复类型注解

# 正确计算项目根目录（从当前文件向上五级）：
# 路径关系：documents.py → management → endpoints → api → src → 项目根目录（E:\zbs_agent）
current_file = Path(__file__).resolve()
project_root = current_file.parent.parent.parent.parent.parent

# 【可选调试】打印路径验证（正式环境可注释）
print(f"当前文件路径：{current_file}")
print(f"计算的项目根目录：{project_root}")

# 将根目录添加到Python路径（确保能导入项目模块）
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
from src.api.schemas.management import UploadResult, DocumentMetadata, DeleteResult  # 假设schemas已定义
from src.management.services.document_service import DocumentService  # 确保service路径正确


# 路由配置（前缀与标签，保持原有功能）
router = APIRouter(
    prefix="/management/documents",
    tags=["management"],
    responses={404: {"description": "资源未找到"}, 500: {"description": "服务器错误"}}
)


def get_document_service() -> DocumentService:
    """依赖注入：提供DocumentService单例（或新实例，根据业务需求）"""
    return DocumentService()


# 1. 文档上传接口（保持原有逻辑）
@router.post(
    "/upload",
    response_model=UploadResult,
    summary="批量上传文档",
    description="支持PDF、TXT、DOCX、MD格式，自动去重和处理，返回成功/失败列表"
)
def upload_documents(
        files: List[UploadFile] = File(..., description="待上传的文档列表"),
        service: DocumentService = Depends(get_document_service)
) -> UploadResult:
    try:
        result = service.process_uploads(files)
        return UploadResult(**result)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理文件失败：{str(e)}")


# 2. 文档列表接口（保持原有逻辑）
@router.get(
    "/list",
    response_model=List[DocumentMetadata],
    summary="获取文档列表",
    description="返回所有文档的元数据（ID、名称、时间、状态等）"
)
def list_documents(
        service: DocumentService = Depends(get_document_service)
) -> List[DocumentMetadata]:
    try:
        metadata_list = service.get_all_metadata()
        return [DocumentMetadata(**item) for item in metadata_list]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取列表失败：{str(e)}")


# 3. 文档删除接口（保持原有逻辑）
@router.delete(
    "/delete/{doc_id}",
    response_model=DeleteResult,
    summary="删除指定文档",
    description="同时删除本地文件、向量库切片和元数据记录"
)
def delete_document(
        doc_id: str,
        service: DocumentService = Depends(get_document_service)
) -> DeleteResult:
    try:
        result = service.delete_document(doc_id)
        if result["status"] == "failed":
            raise HTTPException(status_code=400, detail=result["message"])
        return DeleteResult(**result)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除失败：{str(e)}")


# 4. 文档片段查询接口（关键修复：类型注解 + 异常处理）
@router.get(
    "/{doc_id}/chunks",
    response_model=List[Dict[str, Any]],  # 修正：用typing.Any替代模糊类型
    summary="获取文档的所有切割片段",
    description="返回指定文档的所有切割片段，包含序号、内容、长度等信息"
)
def get_document_chunks(
        doc_id: str,
        service: DocumentService = Depends(get_document_service)
) -> List[Dict[str, Any]]:  # 同步修正返回值类型
    try:
        chunks = service.get_document_chunks(doc_id)
        if not chunks:
            raise HTTPException(
                status_code=404,
                detail=f"文档ID {doc_id} 未找到片段数据（可能未切割或ID错误）"
            )
        return chunks
    except ValueError as e:  # 捕获业务层的ID不存在异常
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:  # 捕获其他未知异常
        raise HTTPException(status_code=500, detail=f"获取片段失败：{str(e)}")